<?php

namespace App\Http\Controllers\Wechat\Send;

use Laravel\Lumen\Routing\Controller as BaseController;
use App\Jobs\SendExpressNoticeJob;


/**
 * 推送通知
 * Class SendExpressNotice
 * @package App\Http\Controllers\Wechat\Messages
 */
class SendExpressNoticeController extends BaseController
{
    public function send()
    {
        $rs = [];

        $expressLists = \App\Models\Express::where('state', '!=', 3)->get();

        foreach ($expressLists as $key => $item) {
            $queryResult = (new \Xu42\ExpressTracking\ExpressTracking($item['nu']))->latestStatus();
            if ((strtotime($queryResult['data'][0]['time'])) > strtotime($item['time'])) {
                // 更新数据库表信息
                $rs[$key]['DbUpdateResult'] = \App\Models\Express::whereId($item['id'])->update([
                    'state'   => $queryResult['state'],
                    'context' => $queryResult['data'][0]['context'],
                    'time'    => $queryResult['data'][0]['time']
                ]);

                $item['time'] = $queryResult['data'][0]['time'];
                $item['com']  = $queryResult['com'];
                // 推送通知
                $rs[$key]['dispatch'] = $this->dispatch(new SendExpressNoticeJob($item));

                // debug
                $rs[$key]['item']        = $item;
                $rs[$key]['queryResult'] = $queryResult;
            }
        }

        return $rs;
    }
}
